package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的将进行对比的密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void insert(EmployeeDTO employeeDTO) {
        //1.执行SQL语句执行的表是Employee，对于前端传输的DTO少了一部分隐式字段。
        // 1.1所以创建employee对象。
        Employee employee = new Employee();
        //1.2将内容赋值给Employee。getter，setter太慢，直接批量赋值
        BeanUtils.copyProperties(employeeDTO, employee);
        //2.设置隐式字段
        //状态
        employee.setStatus(StatusConstant.ENABLE);
        //密码。调用 MD5 的加密算法,并转换为字节数组
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        ////创建时间
        //employee.setCreateTime(LocalDateTime.now());
        ////更新时间
        //employee.setUpdateTime(LocalDateTime.now());

        ////创建人
        //employee.setCreateUser(BaseContext.getCurrentId());
        ////更新人
        employee.setUpdateUser(BaseContext.getCurrentId());
        //3.调用Mapper方法
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult selectAll(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //2.调用Mapper接口查询所有语句,同时兼容模糊查询
        Page<Employee> pageEmps = (Page) employeeMapper.selectAll(employeePageQueryDTO.getName());
        //3.获取总数，并强转为PageResult对象
        return new PageResult(pageEmps.getTotal(), pageEmps.getResult());
    }

    /**
     * 修改员工
     *
     * @param status
     * @param id
     */
    @Override
    public void isUse(Integer status, Long id) {
        //1.因为要与查询一样，同一个SQL包括了员工信息修改功能，所以转化为employee对象
        //可以少写一个SQL语句
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        //2.执行SQL语句
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectById(id);
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //1.因为与修改状态共用一条SQL，所以转换为Employee对象
        Employee employee = new Employee();
        //2.将DAO里的值赋值给Employee。太多了，就不builder的，直接工具类
        BeanUtils.copyProperties(employeeDTO,employee);
        ////3.设置隐式参数信息
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

}
